/*eslint-disable */
import storageApi from '../../core/storage/storage';

@Inject('$log', '$scope', '$compile', '$timeout', '$rootScope', '$state', 'previewTableService', 'iterationTableService', 'documentService', 'ngDialog', 'ngDialogService')
class IterationTableController {
  constructor() {
    this.name = $state.params.name;
    this.tableId = $state.params.id;
    this.historyId = $state.params.historyId;
    this.recordId = $state.params.recordId;
    this.boxId = $state.params.boxId;
    this.type = $state.params.type;

    this.getBoxType(this.boxId);

    this.ue = this.ue_instance = UE.getEditor('container');

    if ($state.params.type == 1) {
      this.$scope.$on('$viewContentLoaded', () => {
        this.initCreate();
      });
    } else if ($state.params.type == 2) {
      this.$scope.$on('$viewContentLoaded', () => {
        this.initHistory();
      });
    }

    // dismiss ueditor instantance and dom structure as if leave this page
    this.$scope.$on('$destroy', () => {
      const ue = this.ue_instance;
      ue && ue.destroy && ue.destroy();

      $('#edui_fixedlayer').remove();
      $('#global-zeroclipboard-html-bridge').remove();
    });
  }

  getBoxType(boxId) {
    // 获取盒子名称或者子盒子名称，用于资料归档
    this.boxType = [];
    this.documentService.getDetailBox(boxId)
      .then((res) => {
        if (res.success) {
          if (res.rows && res.rows.length > 0) {
            if (res.rows.length === 1) {
              res.rows.forEach((item) => {
                this.boxType.push(item);
              });
            }
            if (res.rows.length > 1) {
              res.rows.forEach((item) => {
                if (item.parentId !== -1 && (item.remarks !== '1' || item.remarks !== '2' || item.remarks !== '3')) {
                  this.boxType.push(item);
                }
              });
            }
          }
        } else {
          ngDialogService.alertError(res.message);
        }
      });
  }


  // 资料归档
  mobileDocument(ctrl) {
    this.ngDialog.open({
      template: 'dataArchiving',
      className: 'ngdialog-theme-default pa-confirm-theme pa-confirm-self systemManage-add-dialog',
      controllerAs: 'vm',
      controller($rootScope, $scope, ngDialogService) {
        'ngInject';

        this.view = {
          attachmentFiles: [],
        };

        this.boxType = angular.copy(ctrl.boxType);

        ctrl.ue = this.ue_instance = UE.getEditor('container');

        this.document = {
          orgId: $rootScope.orgId || storageApi.get('orgId'),
          documentName: '',
          documentNumber: '',
          compileTime: '',
          remark: '',
          attachmentIds: [],
          templateId: ctrl.tableId,
          type: ctrl.boxId,
          documentSourceType: 1,
          content: ctrl.ue.getContent(),
        };

        this.document.compileTime = new Date();

        this.submitForm = () => {
          this.document.attachmentIds = this.view.attachmentFiles.map(item => item.id);
          ctrl.documentService.save(this.document)
            .then((res) => {
              if (res.success) {
                ngDialogService.alertSuccess(res.message);
                $scope.closeThisDialog();
                // 缺少单位类型documentType
                // this.$state.go('documentItemMgt', {name: this.name, documentType: this.documentType, boxId: this.boxId});
              } else {
                ngDialogService.alertError(res.message);
              }
            });
        };
      },
    });
  }

  // 保存
  save() {
    this.mapParams = {
      orgId: this.$rootScope.orgId || storageApi.get('orgId'),
      creatorId: this.$rootScope.userId || storageApi.get('userId'),
      templateId: this.tableId,
      templateType: this.boxId,
      content: this.ue.getContent(),
    }
    this.iterationTableService.add(this.mapParams)
      .then((res) => {
        if (res.success) {
          this.ngDialogService.alertSuccess(res.message,);
          this.$state.go('previewTable', {name: this.name, id: this.tableId, boxId: this.boxId});
        } else {
          this.ngDialogService.alertError(res.message);
        }
      });
  }

  initCreate() {
    this.previewTableService
      .get({ id: this.tableId })
      .then((res) => {
        this.previewInfo = res.data;
        this.getCreateUE(this.previewInfo);
      });
  }

  initHistory() {
    this.iterationTableService
      .get({ id: this.historyId })
      .then((res) => {
        this.previewInfo = res.data;
        this.getHostoryUE(this.previewInfo);
      });
  }

  getCreateUE(previewInfo) {
    const ue = this.ue = this.ue_instance;
    UE.ajax.request( '/sgms/api/v1/commonForm/template/findOne?id=' + this.tableId, {

      //请求方法。可选值： 'GET', 'POST'，默认值是'POST'
      method: 'GET',

      //超时时间。 默认为5000， 单位是ms
      timeout: 10000,

      //是否是异步请求。 true为异步请求， false为同步请求
      async: true,

      //请求携带的数据。如果请求为GET请求， data会经过stringify后附加到请求url之后。
      data: {
        name: 'ueditor'
      },

      //请求成功后的回调， 该回调接受当前的XMLHttpRequest对象作为参数。
      onsuccess: function ( xhr ) {
        ue.ready(function () {
          ue.setContent(previewInfo.template);
        });
      },

      //请求失败或者超时后的回调。
      onerror: function ( xhr ) {
        alert( 'Ajax请求失败' );
      }

    });
  }

  getHostoryUE(previewInfo) {
    const ue = this.ue = this.ue_instance;
    UE.ajax.request( '/sgms/api/v1/safetyTable/history/findOne?id=' + this.historyId, {

      //请求方法。可选值： 'GET', 'POST'，默认值是'POST'
      method: 'GET',

      //超时时间。 默认为5000， 单位是ms
      timeout: 10000,

      //是否是异步请求。 true为异步请求， false为同步请求
      async: true,

      //请求携带的数据。如果请求为GET请求， data会经过stringify后附加到请求url之后。
      data: {
        name: 'ueditor'
      },

      //请求成功后的回调， 该回调接受当前的XMLHttpRequest对象作为参数。
      onsuccess: function ( xhr ) {
        ue.ready(function () {
          ue.setContent(previewInfo.content);
        });
      },

      //请求失败或者超时后的回调。
      onerror: function ( xhr ) {
        alert( 'Ajax请求失败' );
      }

    });
  }

}

export default IterationTableController;
